import React, { useEffect, useRef, useState } from "react";
import { Button, Modal, Switch, Table } from "antd";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import axios from "axios";
import UserForm from "../../../components/user-manage/UserForm";
const UserList = () => {
  const [dataSource, setDataSource] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isUpdateOpen, setIsUpdateOpen] = useState(false);
  const [isUpdateDisabled, setIsUpdateDisabled] = useState(false);
  const [roleList, setRoleList] = useState([]);
  const [regionList, setRegionList] = useState([]);
  const [current, setCurrent] = useState([]);
  const addFormRef = useRef();
  const updateFormRef = useRef();
  const columns = [
    {
      title: "區域",
      dataIndex: "region",
      filters: [
        ...regionList.map((item) => ({
          text: item.title,
          value: item.value,
        })),
        {
          text: "全球",
          value: "全球",
        },
      ],
      onFilter: (value, record) => {
        if (value === "全球") {
          return record.region === "";
        }
        return record.region === value;
      },
      render: (item) => {
        return item === "" ? "全球" : item;
      },
    },
    {
      title: "角色名称",
      dataIndex: "roleId",
    },
    {
      title: "用戶名",
      dataIndex: "username",
    },
    {
      title: "用戶狀態",
      dataIndex: "roleState",
      render: (roleState, row) => {
        return (
          <Switch
            checked={row.roleState}
            disabled={row.default}
            onChange={() => onchangeState(row)}
          ></Switch>
        );
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            <Button
              shape="circle"
              type="primary"
              icon={<DeleteOutlined />}
              disabled={item.default}
              onClick={() => deleteUser(item)}
            ></Button>
            <Button
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
              disabled={item.default}
              onClick={() => handleEdit(item)}
            ></Button>
          </div>
        );
      },
    },
  ];

  const {
    role: { roleType },
    username,
    region,
  } = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    const apiUrl ="/users";
    axios.get(apiUrl).then((res) => {
      setDataSource(
        roleType == 1
          ? res.data
          : [
              ...res.data.filter((item) => item.username === username),
              ...res.data.filter(
                (item) => item.region === region && roleType == 3,
              ),
            ],
      );
    });
  }, []);
  useEffect(() => {
    const apiUrl = "/roles";
    axios.get(apiUrl).then((res) => {
      setRoleList(res.data);
    });
  }, []);
  useEffect(() => {
    const apiUrl = "/regions";
    axios.get(apiUrl).then((res) => {
      setRegionList(res.data);
    });
  }, []);

  function addFormOk() {
    addFormRef.current
      .validateFields()
      .then((values) => {
        console.log(values);
        setIsOpen(false);
        addFormRef.current.resetFields();
        axios
          .post("/users", {
            ...values,
            roleState: true,
            default: false,
          })
          .then((res) => {
            setDataSource([
              ...dataSource,
              {
                ...res.data,
                role: roleList.filter((data) => data.id === values.roleId)[0],
              },
            ]);
          });
      })
      .catch((err) => {});
  }
  function deleteUser(item) {
    setDataSource(dataSource.filter((data) => data.id !== item.id));
    axios.delete("/users/" + item.id);
  }

  function handleEdit(item) {
    setIsUpdateOpen(true);
    setCurrent(item);
    setTimeout(() => {
      if (item.roleId == 1) {
        setIsUpdateDisabled(true);
      } else {
        setIsUpdateDisabled(false);
      }
      updateFormRef.current?.setFieldsValue(item);
    }, 1);
  }
  function updateFormOk() {
    updateFormRef.current.validateFields().then((values) => {
      setIsUpdateOpen(false);
      setDataSource(
        dataSource.map((data) => {
          if (data.id === current.id) {
            return {
              ...data,
              ...values,
              role: roleList.filter((data) => data.id === values.roleId)[0],
            };
          }
          return data;
        }),
      );

      axios.patch(
        "/users/" + current.id,
        values,
      );
    });
  }
  function onchangeState(item) {
    item.roleState = !item.roleState;
    setDataSource([...dataSource]);
    axios.patch("/users/" + item.id, {
      roleState: item.roleState,
    });
  }

  return (
    <div>
      <Button type="primary" onClick={() => setIsOpen(true)}>
        添加用戶
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(row) => row.id}
      ></Table>
      <Modal
        open={isOpen}
        title="Create a new collection"
        okText="Create"
        cancelText="Cancel"
        okButtonProps={{
          autoFocus: true,
        }}
        onCancel={() => setIsOpen(false)}
        destroyOnClose
        onOk={addFormOk}
      >
        <UserForm
          ref={addFormRef}
          regionList={regionList}
          roleList={roleList}
        />
      </Modal>

      <Modal
        open={isUpdateOpen}
        title="update collection"
        okText="Update"
        cancelText="Cancel"
        okButtonProps={{
          autoFocus: true,
        }}
        onCancel={() => setIsUpdateOpen(false)}
        destroyOnClose
        onOk={updateFormOk}
      >
        <UserForm
          ref={updateFormRef}
          regionList={regionList}
          roleList={roleList}
          isUpdateDisabled={isUpdateDisabled}
          isUpdate={true}
        />
      </Modal>
    </div>
  );
};

export default UserList;
